package com.food.eat.controller;

import com.food.eat.enums.PayMethod;
import com.food.eat.mapper.OrderProductMapper;
import com.food.eat.pojo.OrderProduct;
import com.food.eat.pojo.vo.SumbitOrderVo;
import com.food.eat.util.FoodResultJson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.n3r.idworker.Sid;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author:RenPu
 * @Date: 2020/7/18 16:49
 * @Version: 1.0
 * @description:
 */

@Slf4j
@Api(value = "订单案例相关的接口", tags = {"订单案例相关的接口"})
@RequestMapping("orders")
@RestController
public class OrderController {

    @Resource
    private Sid sid;

    @Resource
    private RabbitTemplate rabbitTemplate;

    private final static Map<String, AtomicInteger> skuMappingSum = new HashMap<>();

    @Autowired
    private OrderProductMapper orderProductMapper;

    @ApiOperation(value = "订单创建接口", notes = "订单创建接口", httpMethod = "POST")
    @PostMapping(value = "create")
    public FoodResultJson create(@RequestBody SumbitOrderVo sumbitOrder) {

        if (sumbitOrder.getPayMethod().equals(PayMethod.ZHIBAO.type) && sumbitOrder.getPayMethod().equals(PayMethod.WEIXIN.type)) {
            return FoodResultJson.errMsg("请选择支付方式！！！！");
        }


        System.out.println(sumbitOrder);

        return FoodResultJson.ok();
    }


    /**
     * 初始化，商品数据
     * @return
     */
    @GetMapping("/initDataBase")
    public FoodResultJson initDataBase() {
        for (int i = 0; i < 100; i++) {
            OrderProduct orderProduct = new OrderProduct();
            orderProduct.setProductId(sid.nextShort());
            orderProduct.setProductName("尊贵商品茅子" + i + "号");
            orderProduct.setStoregeNum(i);
            orderProduct.setCreateOpereatorId(1);
            orderProductMapper.insert(orderProduct);
        }
        return FoodResultJson.ok();
    }


    /**
     * 预加载商品数据到内存，用于预扣库存减免数据库压力
     * @return
     */
    @GetMapping("/advanceDataToDataBase")
    @PostConstruct
    public FoodResultJson advanceDataToDataBase() {
        List<OrderProduct> orderProducts = orderProductMapper.selectByExample(null);
        for (OrderProduct orderProduct : orderProducts) {
            skuMappingSum.put(orderProduct.getProductId(), new AtomicInteger(orderProduct.getStoregeNum()));
        }

        return FoodResultJson.ok();
    }


    /**
     * 抢购接口
     *
     * @param productId
     * @return
     */
    @GetMapping("/goStart")
    public FoodResultJson goStart(String productId) {

        for (int i = 0; i < 20; i++) {
            new Thread(() -> {
                int count = 0;
                //商品数量扣减
                while (skuMappingSum.get(productId).getAndDecrement() > 0) {
                    long id = Thread.currentThread().getId();

                    //用户抢到的商品，发送到MQ用于异步生成
                    // 秒杀订单，库存数据扣减
                    rabbitTemplate.convertAndSend("promotion.order", id + "," + productId);
                    count++;
                    log.info("当前线程:{},抢到商品的数量为:{}", Thread.currentThread().getId(), count);
                }
            }).start();
        }


        return FoodResultJson.ok();
    }


    @GetMapping(value = "testMq")
    public FoodResultJson testMq(){
        rabbitTemplate.convertAndSend("promotion.order", "你好，小兔子");
        return FoodResultJson.ok();
    }

}
